import React, { useEffect, useState, useRef } from 'react';
import { Table, Button, Input, DatePicker, Tabs, Space, Pagination, message, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import request from '@/utils/request';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';
import './ReleaseHistory.css';

type StatusKey = 0 | 1 | 2 | 3 | 4 | 'all';

const statusMap: Record<StatusKey, string | undefined> = {
  all: undefined,
  1: '发布成功',
  0: '发布失败',
  2: '待发布',
  3: '发布中'
};

const statusColor: Record<Exclude<StatusKey, 'all'>, string> = {
  1: 'green',
  0: 'red',
  2: 'orange',
  3: 'blue',
  4: 'gray'
};

const ReleaseHistory: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [releaseCount, setReleaseCount] = useState<any>({});
  const [status, setStatus] = useState<any>('all');
  const [taskId, setTaskId] = useState('');
  const [releaseTime, setReleaseTime] = useState<any>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const navigate = useNavigate();

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 89;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  const fetchReleaseCount = async () => {
    try {
      const res = await request.get('/Management/DataReleaseStatusCount', {
        params: {
          release_task_id: taskId || undefined,
          release_task_time__gte: releaseTime && releaseTime[0] ? dayjs(releaseTime[0]).format('YYYY-MM-DD 00:00:00') : undefined,
          release_task_time__lte: releaseTime && releaseTime[1] ? dayjs(releaseTime[1]).format('YYYY-MM-DD 23:59:59') : undefined
        }
      });
      if (res.status === 200 && res.data.data) {
        setReleaseCount(res.data.data);
      }
    } catch (e: any) {
      message.error(e?.message || '获取发布数量统计失败');
    }
  };

  const fetchData = async (params = {}, silent = false) => {
    if (!silent) {
      setLoading(true);
    }
    try {
      const res = await request.get('/Management/DataListReleaseSearch', {
        params: {
          page,
          page_size: pageSize,
          release_task_id: taskId || undefined,
          release_task_time__gte: releaseTime && releaseTime[0] ? dayjs(releaseTime[0]).format('YYYY-MM-DD 00:00:00') : undefined,
          release_task_time__lte: releaseTime && releaseTime[1] ? dayjs(releaseTime[1]).format('YYYY-MM-DD 23:59:59') : undefined,
          status: status !== 'all' ? status : undefined,
          ...params
        }
      });
      if (res.status === 200 && res.data.data) {
        setData(res.data.data.list || []);
        setTotal(res.data.data.count || 0);
      }
    } catch (e: any) {
      message.error(e?.message || '获取发布历史失败');
    } finally {
      if (!silent) {
        setLoading(false);
      }
    }
  };

  useEffect(() => {
    fetchData();
    fetchReleaseCount();
    // eslint-disable-next-line
  }, [page, pageSize, status]);

  // 计算表格滚动高度并监听窗口大小变化
  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  // 定时静默刷新
  useEffect(() => {
    const timer = setInterval(() => {
      fetchData({}, true);
      fetchReleaseCount();
    }, 5000);
    return () => {
      clearInterval(timer);
    };
  }, [page, pageSize, status, taskId, releaseTime]);

  const handleSearch = () => {
    setPage(1);
    fetchData({ page: 1 });
    fetchReleaseCount();
  };

  const handleClear = () => {
    setTaskId('');
    setReleaseTime(null);
    setPage(1);
    fetchData({ page: 1, release_task_id: undefined, release_task_time__gte: undefined, release_task_time__lte: undefined });
    fetchReleaseCount();
  };

  const handleBatchContinue = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择需要断点续推的任务');
      return;
    }

    try {
      const res = await request.post('/Management/DataReleaseBreakpointContinuation', {
        release_task_ids: selectedRowKeys
      });
      if (res.status === 200) {
        message.success('批量断点续推成功');
        setSelectedRowKeys([]);
        fetchData();
        fetchReleaseCount();
      }
    } catch (e: any) {
      message.error(e?.message || '批量断点续推失败');
    }
  };

  const handleSingleContinue = async (taskId: string) => {
    try {
      const res = await request.post('/Management/DataReleaseBreakpointContinuation', {
        release_task_ids: [taskId]
      });
      if (res.status === 200) {
        message.success('断点续推成功');
        fetchData();
        fetchReleaseCount();
      }
    } catch (e: any) {
      message.error(e?.message || '断点续推失败');
    }
  };

  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    getCheckboxProps: (record: any) => ({})
  };

  const columns: ColumnsType<any> = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (_: any, __: any, idx: number) => idx + 1 + (page - 1) * pageSize,
      width: 60
    },
    {
      title: '任务id',
      dataIndex: 'task_name',
      width: 120
    },
    {
      title: '文件个数',
      dataIndex: 'files_count',
      width: 100
    },
    {
      title: '数据总量(MB)',
      dataIndex: 'files_size',
      width: 120,
      render: (value: number) => {
        if (value === null || value === undefined) return '-';
        return (value / (1024 * 1024)).toFixed(2);
      }
    },
    {
      title: '发布开始时间',
      dataIndex: 'release_start_time',
      width: 180
    },
    {
      title: '发布结束时间',
      dataIndex: 'release_end_time',
      width: 180
    },
    {
      title: '发布状态',
      dataIndex: 'status',
      width: 100,
      render: (val: StatusKey, record: any) => (
        <Tooltip title={val === 0 ? record.error_message : ''}>
          <span style={{ color: statusColor[val as Exclude<StatusKey, 'all'>] }}>{statusMap[val] || '-'}</span>
        </Tooltip>
      )
    },
    {
      title: '成功条数',
      dataIndex: 'release_success_count',
      width: 100
    },
    {
      title: '失败条数',
      dataIndex: 'release_fail_count',
      width: 100
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 120,
      align: 'center' as const,
      render: (_: any, record: any) => (
        <Space>
          <Button type="link" size="small" onClick={() => navigate(`/release-detail/${record.id}`)}>
            发布详情
          </Button>
          {record.status === 0 && (
            <Button type="link" size="small" onClick={() => handleSingleContinue(record.id)}>
              断点续推
            </Button>
          )}
        </Space>
      )
    }
  ];

  // Tab统计
  const tabItems = [
    { key: 'all', label: `全部(${releaseCount.all || 0})` },
    { key: 1, label: `发布成功(${releaseCount.success_release || 0})` },
    { key: 0, label: `发布失败(${releaseCount.fail_release || 0})` },
    { key: 2, label: `待发布(${releaseCount.be_release || 0})` },
    { key: 3, label: `发布中(${releaseCount.under_release || 0})` }
  ];

  return (
    <div style={{ position: 'relative', flex: 1 }}>
      <div style={{ position: 'absolute', width: '100%', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ marginBottom: 16, fontSize: 14 }}>
          <Button 
            type="link" 
            icon={<ArrowLeftOutlined />} 
            onClick={() => window.history.back()}
            style={{ padding: 0, marginRight: 10 }}
          >
            返回
          </Button>
          数据管理 / 发布历史
        </div>
        <div style={{ marginBottom: 10 }} className="filter-form">
          <Space>
            <Input placeholder="请输入发布任务的关键字" value={taskId} onChange={(e) => setTaskId(e.target.value)} style={{ width: 200 }} />
            <DatePicker.RangePicker
              value={releaseTime}
              onChange={setReleaseTime}
              style={{ width: 320 }}
              placeholder={['选择发布时间', '选择发布时间']}
            />
            <Button type="primary" onClick={handleSearch}>
              筛选
            </Button>
            <Button onClick={handleClear}>清除</Button>
          </Space>
        </div>
        <Tabs
          activeKey={status}
          onChange={(key) => {
            setStatus(key === 'all' ? 'all' : Number(key));
            setPage(1);
          }}
          items={tabItems}
          className="release-history-tabs"
        />
        <div className="release-table-container" ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={data}
            loading={loading}
            pagination={false}
            bordered
            size="small"
            scroll={{ y: tableScrollY, x: 'max-content' }}
            rowSelection={rowSelection}
            footer={() => (
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Button type="primary" danger disabled={selectedRowKeys.length === 0} onClick={handleBatchContinue}>
                  断点续推
                </Button>
                <Pagination
                  current={page}
                  pageSize={pageSize}
                  total={total}
                  showSizeChanger
                  pageSizeOptions={['10', '20', '50']}
                  onChange={(p, s) => {
                    setPage(p);
                    setPageSize(s!);
                  }}
                  showTotal={(t) => `共 ${t} 条记录`}
                />
              </div>
            )}
          />
        </div>
      </div>
    </div>
  );
};

export default ReleaseHistory;
